<template>
  <el-form label-width="80px">
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称"    v-model="spuInfo.spuName"></el-input>
    </el-form-item>
    <el-form-item label="品牌">
      <el-select placeholder="请选择" v-model="spuInfo.tmId">
        <el-option v-for="tm in tmList" :key="tm.id" :value="tm.id" :label="tm.tmName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" placeholder="SPU名称" rows="4" v-model="spuInfo.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="spuImageList "
        :action= "`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select :placeholder="`还有${unUsedSaleAttrList.length}个未选`"  v-model="tempSaleAttr">
        <el-option
          v-for="attr in unUsedSaleAttrList"
          :key="attr.id"
          :value="`${attr.id}:${attr.name}`"
          :label="attr.name"
          />
      </el-select>
      <el-button type="primary" size="default" icon="ele-Plus" @click="addSaleAttr" :disabled="!tempSaleAttr"
        >添加销售属性</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-table :data="spuSaleAttrList" border stripe>
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{row}">
            <el-tag
                  v-for="tag in row.spuSaleAttrValueList"
                  :key="tag"
                  class="mx-1"
                  closable
                  :disable-transitions="false"
                  @close=""
                >
                  {{ tag.saleAttrValueName}}
                </el-tag>
                <el-input
                v-if="row.isEdit"
                  ref="editEle"
                  class="ml-1 w-20"
                  size="small"
                  v-model="row.inputValue"
                  @blur="handleInputConfirm(row,$event)"
                />
                <el-button 
                class="button-new-tag ml-1" 
                size="small" 
                @click="changeToEdit(row)" 
                v-else  
                  >
                  添加新属性
                </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-button type="danger" size="default" @click="spuSaleAttrList.splice($index,1)" icon="ele-Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="default" size="default" @click="emit('setState', 0)"
        >取消</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
  
import { ref ,onMounted, computed, nextTick} from "vue";
import { 
  requestBaseSaleAttrList, 
  requestSpuImgList, 
  requestSpuSaleAttrList, 
  type BaseSaleAttrListType, 
  type SpuImgListType, 
  type SpuInfoType, 
  type SpuSaleAttrItemType, 
  type SpuSaleAttrListType ,
  requestSaveSpuInfo,
  requestUpdateSpuInfo
} from "@/api/spu";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import {ElMessage} from "element-plus";
import { requestAllTmList, type TmListType } from "@/api/trademark";
//Spu照片墙的逻辑
// const fileList = ref<UploadUserFile[]>([
//   {
//     name: "food.jpeg",
//     url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
//   },
//   {
//     name: "food.jpeg",
//     url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
//   },
// ]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//接受自定义事件
const emit = defineEmits<{
  (event:"setState",state:number,row?:SpuInfoType):void
}>()
//接受传过来得值
const prop = defineProps<{
  spuInfo:SpuInfoType
}>()
//进入当前页面需要调用函数，包括（1.品牌列表，2.所有在售属性列表 3.spu图片列表 4.当前spu属性列表）
//首选声明四个数据用来保存四个请求回来得到的数据
const  tmList =ref<TmListType[]>([])
const saleAttrList=ref<BaseSaleAttrListType> ([])
const spuImageList=ref<SpuImgListType>([])
const spuSaleAttrList=ref<SpuSaleAttrListType>([])
//声明一个函数调用
const getAllUseData = async () => {
  //如果父组件传过来得数据有id说明就是回填数据,否则就是新数据，新数据只用拿到品牌列表和所在属性列表
  if (!prop.spuInfo.id) {
    //说明是新增请求，只发送2个请求
    //请求品牌列表
    const result1 = await  requestAllTmList()
    tmList.value = result1
    //请求在售商品列表
    const result2 = await  requestBaseSaleAttrList()
    saleAttrList.value = result2
  } else {
    //如果没有id表示是回到数据
    //会发送四个请求
    const promise1 = requestAllTmList()
    const promise2 = requestBaseSaleAttrList()
    const promise3 = requestSpuImgList(prop.spuInfo.id)
    const promise4 = requestSpuSaleAttrList(prop.spuInfo.id)
    const result = await Promise.all([promise1, promise2, promise3, promise4])
    //将值一一传递到state中
    tmList.value = result[0]
    saleAttrList.value = result[1]
    spuImageList.value = result[2]
    //处理照片墙的数据
    spuImageList.value.forEach((item)=>{
        item.name = item.imgName;
        item.url = item.imgUrl;
      })
    spuSaleAttrList.value = result[3]
    spuSaleAttrList.value.forEach((item)=>{
      item.isEdit = false;
      //添加一个内容属性
      item.inputValue = "";
    })
  }
}
  //进入页面的时候就调用函数
  onMounted(() => {
   getAllUseData()
  })
//.nev
  const baseUrl = import.meta.env.VITE_API_URL  

  const unUsedSaleAttrList = computed(()=>{
    return   saleAttrList.value =  saleAttrList.value.filter((item1)=>{
        return spuSaleAttrList.value.every((item2)=>{
          return item2.saleAttrName != item1.name
        })
      })
  })

//创建一个新值
const tempSaleAttr =ref("")
//点击添加属性的时候
const addSaleAttr=()=>{
  const [baseSaleAttrId,saleAttrName] = tempSaleAttr.value.split(":")
  //拼接属性值数据
  const tempSpuSaleAttr ={
    baseSaleAttrId:+baseSaleAttrId,
    saleAttrName:saleAttrName,
    spuSaleAttrValueList:[]
  }
  spuSaleAttrList.value.push(tempSpuSaleAttr)
  //清空临时数据
  tempSaleAttr.value =""

}
//获取ref组件
const editEle = ref()

const changeToEdit=(row:SpuSaleAttrItemType)=>{
  //切换模式
    row.isEdit = true;
    //自动获取焦点
    nextTick(()=>{
      editEle.value.focus()
    })
}
//失去焦点后
const handleInputConfirm=(row:SpuSaleAttrItemType,e:Event)=>{
  //获取当前输入的内容
  let inputValue= row.inputValue as string
  if(!inputValue.trim()){
    //如果输入的数据是控制 ,变成soan标签
    row.isEdit = false;
    ElMessage.error("添加的值不能为空")
    return
  }
  //在判断是否有重复的
  const isRepeat = row.spuSaleAttrValueList.some((item)=>{
    return item.saleAttrValueName ===inputValue
  })
  if(isRepeat){
    //如果有重复
    ElMessage.error("添加的属性值有重复");
    row.inputValue=""
    row.isEdit = false;
  }

  //然后就是没有重复的且不为空的值 就可以传给当前数据
  //创建一个新值
  const newSaleAttrValue ={
    baseSaleAttrId : row.baseSaleAttrId,
    saleAttrValueName : row.inputValue as string
  }
  //将新值添加给数据
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //最后清空数据,并且添加转成span标签
  row.inputValue = ""
  row.isEdit = false;

}

//点击保存
const save = async ()=>{
  //首先第一肯定是要收集图片
  const newSpuImageList = spuImageList.value.map((item)=>{
    //利用map映射，如果有是新增加的图片，返回得事url在data里面
    if(item.response){
      //将新增的图片地址放入item中的imgurl中
      return {
        imgUrl:item.response.data as string,
        imgName:item.name as string
      }
    }else{
      //如果没有新政图片
      return{
        imgUrl:item.imgUrl,
        imgName:item.imgName
      }
    }
  })

    //然后整理spuSaleAttrList的数据  内部数据增加了 isEdit/inputValue2个属性
    spuSaleAttrList.value.forEach((item)=>{
      delete item.isEdit
      delete item.inputValue
    })

    //然后将整理好的数据放到spuInfo中
    prop.spuInfo.spuImageList = newSpuImageList
    prop.spuInfo.spuSaleAttrList = spuSaleAttrList.value

    //发送请求
    try {
      //首先判断是新增还是更新
      if(prop.spuInfo.id){
        //有id说明是更新
      await  requestUpdateSpuInfo(prop.spuInfo)
      ElMessage.success("更新数据成功")
      }else{
        //否则就是增加
        await requestSaveSpuInfo(prop.spuInfo)
        ElMessage.success("添加数据成功")
      }

    } catch (error) {
      ElMessage.error("跟新失败或者添加数据失败 ")
    }
    //最后回到spulist页面
    emit("setState",0 )
}
</script>
